import static javax.swing.JOptionPane.*
import javax.swing.JFileChooser
import javax.swing.ProgressMonitor
import com.ipodget.*

class IpodGetController {
    def model
    def view
    def ipod

    
    def deleteSelection = {
    	if(!view.searchResultTable.selectedRowCount){
        	String message = "Select some songs to delete..."
	        showMessageDialog(app.appFrames[0], message, "Nothing to delete!", INFORMATION_MESSAGE)
    	} else {
    	    boolean indexNeedsUpdating = false
	        doOutside {
	            ProgressMonitor monitor = new ProgressMonitor(app.appFrames[0], "Deleting songs...", "Initializing...", 0, view.searchResultTable.selectedRows.length)
		        showMessageDialog(app.appFrames[0], "Sure you want to delete the ${view.searchResultTable.selectedRows.size()} select songs?", "Are you sure?", INFORMATION_MESSAGE)
    	    	view.searchResultTable.selectedRows.eachWithIndex { indexSelected, indexWithinSelection ->
    	        	def song = model.searchResults[indexSelected]
    	        	monitor.note = "Deleting ${song.title}..."
    	        	monitor.progress = indexWithinSelection
    	        	def songFile = new File(song.filename)
    	        	if(songFile.delete()){
    	        	    println "Song ${song.title} (${song.filename}) was deleted!"
    	        	    indexNeedsUpdating = true
    	        	} else {
    	        	    println "Song ${song.title} (${song.filename}) was not deleted!"
    	        	    monitor.note = "File ${song.filename} was not deleted!"
    	        	    songFile.deleteOnExit()
    	        	}
    	    	}
	            if(indexNeedsUpdating){
	                monitor.note = "Should be updating index..."
	                // FIXME index needs updating... implement
	            }
    	    	monitor.close()
	        }
    	}
    }
    
    /**
     * Download the current selectrion of songs
     */
    def downloadSelection = {
    	if(!view.searchResultTable.selectedRowCount){
        	String message = "Select some songs to download..."
	        showMessageDialog(app.appFrames[0], message, "Nothing to get!", INFORMATION_MESSAGE)
    	} else {
    	    def fc = new JFileChooser()
    	    fc.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
    	    if (fc.showDialog(app.appFrames[0], "Download") == JFileChooser.APPROVE_OPTION) {
    	        doOutside {
    	            File targetDirectory = fc.selectedFile	    		
    	            ProgressMonitor monitor = new ProgressMonitor(app.appFrames[0], "Downloading songs...", "Initializing...", 0, view.searchResultTable.selectedRows.length)
        	    	view.searchResultTable.selectedRows.eachWithIndex { indexSelected, indexWithinSelection ->
        	        	def song = model.searchResults[indexSelected]
        	        	monitor.note = "Copying ${song.title}..."
        	        	monitor.progress = indexWithinSelection
            	        copySong(song, targetDirectory)
        	    	}
        	    	monitor.close()
    	        }
    	    }
    	}
    }
    
    /**
     * Copy a song to the user's file system
     * This will create a structure in the file system
     *    ARTIST/ALBUM/SONG.mp3
     * @param song the song for the index to copy
     * @param targetRoot the root folder where the music will be written
     */
	def copySong = { song, targetRoot ->
		File folder = new File(targetRoot, "${song.artist}/${song.album}")
		File songFile = new File(folder, "${song.title}.mp3")
		if(!folder.exists()){
			log.debug "creating directories for ${songFile.canonicalPath}"
			folder.mkdirs()
		}
		def source = new File(song.filename)
		log.debug "Copying ${source.canonicalPath} to ${songFile.canonicalPath}"
		def reader = source.newInputStream()
		songFile.withOutputStream { writer ->
			writer << reader
		}
		reader.close()
		log.debug " done!"
	}

    /**
     * Run a search on the ipod
     */
    def search = {
        def results = null
        doOutside {
            model.searchResults = ipod.search(model.searchString, null)
            doLater {
        		view.searchResultTable.model = app.builders.root.tableModel(list: model.searchResults) {
        			propertyColumn(header:'Artist', propertyName:'artist')
        			propertyColumn(header:'Album', propertyName:'album')
        			propertyColumn(header:'Title', propertyName:'title')
        		}
            }
        }
    }
    
    /**
     * Create the ipod-get index
     */
    def index = {
		ProgressMonitor monitor = new ProgressMonitor(view.searchField, "Indexing Ipod", "Initializing...", 0, ipod.countMusicFiles())
		def songNumber = 0
        doOutside {
    		ipod.index {
    		    songNumber += 1
    			monitor.progress = songNumber
    			monitor.note = it 
    		}
		}
    }
    
    /**
     * First attempt to re-use last mount point. If that fails,
     * ask the user for the place where the ipod is connected
     */
    def initializeIpodConnection = {
        try {
            def lastMountPoint = Settings.getLastKnownMountPoint()
            if(lastMountPoint){
                this.ipod = new Ipod(lastMountPoint)
                return
            }
        } catch (IpodNotFoundException nfe) {
            log.warn('Ipod not found on previous mount point... asking user!')
        }
	    def fc = new JFileChooser()
	    fc.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
	    if (fc.showDialog(app.appFrames[0], "Where is the ipod?") == JFileChooser.APPROVE_OPTION) {
	        File mountPoint = fc.selectedFile
	        try {
	        	this.ipod = new Ipod(mountPoint)
	        } catch (IpodNotFoundException nfe) {
	        	String message = "<html>Ipod could not be found on the selected location.<br><i>Location: </i>${mountPoint.canonicalPath}<br><i>Message: </i>${nfe.message}</html>"
	        	showMessageDialog(app.appFrames[0], message, "Can't find Ipod!", ERROR_MESSAGE)
	        	app.shutdown()
	        }
	        Settings.setLastKnownMountPoint(mountPoint)
	   		if(ipod.isIndexingNeeded() && 
	   			YES_OPTION == showConfirmDialog(view.searchField, "Want to index the ipod now?")) {
	   		    index()
	   		}
	    } else {
	    	app.shutdown()
	    }
    }
    
    private void showDialog( dialogName ) {  
		def dialog = view."$dialogName"  
		if( dialog.visible ) return  
		dialog.pack()  
		int x = app.appFrames[0].x + (app.appFrames[0].width - dialog.width) / 2  
		int y = app.appFrames[0].y + (app.appFrames[0].height - dialog.height) / 2  
		dialog.setLocation(x, y)  
		dialog.show()  
    }  
    
    def exit = {
    	app.shutdown()
    }
}